package com.mofang.powerdekorhelper.persenter;


import com.mofang.powerdekorhelper.base.BasePresent;
import com.mofang.powerdekorhelper.model.ResultMessage4;
import com.mofang.powerdekorhelper.utils.Constants;
import com.mofang.powerdekorhelper.utils.UrlTools;
import com.mofang.powerdekorhelper.utils.http.InitRetrofit;
import com.mofang.powerdekorhelper.utils.http.RetrofitSerives;
import com.mofang.powerdekorhelper.view.InvalidataView;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by luofei on 2017/7/13 0013.
 */

public class InvalidataPersenter extends BasePresent<InvalidataView> {

    RetrofitSerives retrofitSerives;
    Call<ResultMessage4> call;

    public void getQrCode(int type, int value, boolean ishyaline) {

        view.showProgress();

        retrofitSerives = InitRetrofit.getInstance().getRetrofit(UrlTools.Services);

        String jsonParams = getParams(type, value, ishyaline);

        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonParams);

        call = retrofitSerives.getQrcode(body);

        call.enqueue(new Callback<ResultMessage4>() {
            @Override
            public void onResponse(Call<ResultMessage4> call, Response<ResultMessage4> response) {
                if (response.isSuccessful()) {
                    if (response.body().getCode().equals("0")) {
                        view.setQrCode(response.body().getResult());
                        view.hideProgress();
                    } else {
                        view.onError(Constants.GTEQRCODE_FAIL_INFO);
                    }
                } else {
                    view.onError(Constants.GTEQRCODE_FAIL_INFO);
                }
            }

            @Override
            public void onFailure(Call<ResultMessage4> call, Throwable t) {
                view.onError(Constants.GTEQRCODE_FAIL_INFO);
            }
        });
    }

    private String getParams(int type, int value, boolean ishyaline) {
        JSONObject paramsJson = new JSONObject();
        try {
            paramsJson.put("type", type);
            paramsJson.put("value", value);
            paramsJson.put("ishyaline", ishyaline);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return paramsJson.toString();
    }

    @Override
    public void stopRequest() {
        if (call != null) {
            call.cancel();
        }
    }
}
